#!/bin/bash

if [ $# != 2 ] || ([ $1 != "nocover" ] && [ $1 != "cover" ] && [ $1 != "quick" ])
then
    echo "Usage: ci-build cover|nocover|quick ODBC_PASSWORD"
    exit 1
fi

TOOLS=`dirname $0`
if [ `uname` = "Darwin" ]; then
    BASE=$(cd "$TOOLS/.."; pwd -P)
else
    BASE=`readlink -f $TOOLS/..`
fi

$TOOLS/set-odbc-password vars $2
make devclean devrel

EJD1=$BASE/dev/mongooseim_node1
EJD2=$BASE/dev/mongooseim_node2
EJD1CTL=$EJD1/bin/mongooseim
EJD2CTL=$EJD2/bin/mongooseim
SUMMARIES_DIRS=$BASE'/test/ejabberd_tests/ct_report/ct_run*'
SQL_SCRIPTS=`ls -dt $EJD1/lib/ejabberd-2.1.8*/priv | head -1`

# WARNING: database starting scripts are specific to our Jenkins CI machine
sudo nohup mysqld_safe &
sleep 5
mysql -h localhost -u ejabberd -p$2 -e 'drop database if exists ejabberd'
mysql -h localhost -u ejabberd -p$2 -e 'create database ejabberd'
mysql -h localhost -u ejabberd -p$2 ejabberd < $SQL_SCRIPTS/mysql.sql

sudo service postgresql start
export PGPASSWORD=$2
psql -U postgres -c "drop database if exists ejabberd"
psql -U postgres -c "create database ejabberd"
psql -h localhost -U ejabberd -q -d ejabberd -f $SQL_SCRIPTS/pg.sql

sudo service slapd start

$TOOLS/redis start

echo -n "starting MongooseIM node 1: "
$EJD1CTL start && echo ok || echo failed
echo -n "starting MongooseIM node 2: "
$EJD2CTL start && echo ok || echo failed
sleep 1
echo -n "pinging MongooseIM node 1: "
$EJD1CTL ping
echo -n "pinging MongooseIM node 2: "
$EJD2CTL ping

make test_deps
$TOOLS/set-odbc-password test $2
if [ $1 == "nocover" ]
then
    cd test/ejabberd_tests; make test TESTSPEC=full.spec; cd ../..
elif [ $1 == "quick" ]
then
    make quicktest
else
    make cover_test
fi
RAN_TESTS=`cat /tmp/ct_count`

echo -n "stopping MongooseIM node 1: "
$EJD1CTL stop
echo -n "stopping MongooseIM node 2: "
$EJD2CTL stop

$TOOLS/redis stop

if [ `uname` = "Darwin" ]; then
    SUMMARIES_DIR=`ls -dt $SUMMARIES_DIRS | head -n $RAN_TESTS`
else
    SUMMARIES_DIR=`eval ls -d $SUMMARIES_DIRS --sort time | head -n $RAN_TESTS`
fi

$TOOLS/summarise-ct-results $SUMMARIES_DIR
CT_STATUS=$?

echo
echo "All tests done."
if [ $CT_STATUS == 0 ]
then
    echo "Build succeeded"
else
    echo "Build failed"
fi
exit $CT_STATUS
